package com.anyikang.volunteer.sos.volunteer.app.sos;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.anyikang.volunteer.sos.volunteer.R;
import com.anyikang.volunteer.sos.volunteer.app.MyConstant;
import com.anyikang.volunteer.sos.volunteer.app.adapter.SosRecordAdapter;
import com.anyikang.volunteer.sos.volunteer.app.bean.SosListData;
import com.anyikang.volunteer.sos.volunteer.app.bean.SosListItem;
import com.anyikang.volunteer.sos.volunteer.app.bean.SosListJson;
import com.anyikang.volunteer.sos.volunteer.app.bean.User;
import com.anyikang.volunteer.sos.volunteer.app.spot.SpotFragment;
import com.anyikang.volunteer.sos.volunteer.app.view.MyScrollListView;
import com.anyikang.volunteer.sos.volunteer.app.view.RefreshScrollviewLayout;
import com.anyikang.volunteer.sos.volunteer.utils.MyErrorDeal;
import com.google.gson.Gson;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;

import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author xw.gao
 * @version 2017/6/17
 * @git http://60.205.139.138:81/root/GSMServerAPP.git
 */
public class HelpingFragment extends SpotFragment implements SwipeRefreshLayout.OnRefreshListener,
        RefreshScrollviewLayout.OnLoadListener {

    MyScrollListView lvRecords;
    RefreshScrollviewLayout swipeLayout;

    String TAG = "HelpingFragment"+"_gxw";

    private ArrayList<SosListItem> mSosList = new ArrayList<SosListItem>();
    SosRecordAdapter mAdapter;
    private View layout;
    int pageIndex = 1;
    private boolean hasNextPage = false;
    private Activity mActivity;
    private Handler mHandler;
    private final int REFRESH_LIST = 0;  //刷新列表
    private final int LOAD_MORE = 1;   //加载更多
    int pageSize = 20;
    // TODO: Rename and change types and number of parameters
    public static HelpingFragment newInstance(String userId) {
        HelpingFragment fragment = new HelpingFragment();
        Bundle args = new Bundle();
        args.putString("userId", userId);
        fragment.setArguments(args);
        return fragment;
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view

        if (layout == null) {
            layout = inflater.inflate(R.layout.fragment_helping, container, false);
        }
        createHandler();
        initView();
        autoRefresh(); //自动刷新
        Log.i(TAG,"onCreateView");
        return layout;
    }
    /**
     * 初始化视图
     */
    private void initView() {

        lvRecords = (MyScrollListView) layout.findViewById(R.id.lvRecords);
        mAdapter = new SosRecordAdapter(mSosList,mActivity,"");
        lvRecords.setAdapter(mAdapter);
        lvRecords.setOverscrollHeader(getResources().getDrawable(R.mipmap.ic_launcher));

        swipeLayout = (RefreshScrollviewLayout) layout.findViewById(R.id.swipe_container);
        swipeLayout.setLoadingLayout((LinearLayout)layout.findViewById(R.id.listLayout));
        swipeLayout.setColorSchemeResources(R.color.color_bule,
                R.color.green,
                R.color.color_bule,
                R.color.green_50bc31);
        swipeLayout.setSize(SwipeRefreshLayout.DEFAULT);
        swipeLayout.setOnRefreshListener(this);
        swipeLayout.setOnLoadListener(this);

    }



    @Override
    public void onAttach(Context context) {
        mActivity = (Activity) context;
        super.onAttach(context);
    }




    public void createHandler()
    {
        mHandler = new Handler() {
            @Override
            public void handleMessage(android.os.Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 0:
                        mAdapter.notifyDataSetChanged();
                        break;
                    default:
                        Log.i(TAG, "Unhandled msg - " + msg.what);
                }
            }
        };
    }

    /**
     * 获取成功
     */
    public void  dealGetSuccess(SosListData data, int operation) {

        hasNextPage = data.isHasNextPage();

        if (operation == REFRESH_LIST)
        {
            if(mSosList != null)
            {
                mSosList.clear();
            }
        }

        ArrayList<SosListItem> sosListItem =  data.getList();

        if(sosListItem!=null && sosListItem.size()>0)
        {
            mSosList.addAll(sosListItem);
        }
        mAdapter.notifyDataSetChanged();


        if(hasNextPage)
        {
            //gxw-  hasNextPage = true;
            pageIndex++;
        }
        else {
            //gxw- hasNextPage = false;
        }
        return;
    }
    /**
     * 获取服务端 任务单全部状态的数据
     */

    private void getData(final int operation) {
       //gxw- getAllRecords(operation);

        User user = new User(mActivity);
        String token = user.getUserToken();
        int type = 2;

        Log.i(TAG,"url ="+ MyConstant.API_SOS_LIST + "token="+token+",type="+type);
        OkHttpUtils
                .get(MyConstant.API_SOS_LIST)//
                .tag(MyConstant.API_SOS_LIST)//
                .params("tokenId", token)//
                .params("pageIndex", String.valueOf(pageIndex))//
                .params("pageSize", String.valueOf(pageSize))//
                .params("type",String.valueOf(type))
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {

                        swipeLayout.setRefreshing(false);
                        swipeLayout.setLoading(false);

                        int retCode = response.code();
                        if(retCode == 200)
                        {
                            Log.i(TAG,"onSuccess 200 return："+s);
                            try
                            {
                                SosListJson sosListJson = new Gson().fromJson(s,SosListJson.class);

                                if(sosListJson.getStatus() == 1)//查询全部状态成功
                                {
                                    //登录成功
                                    dealGetSuccess(sosListJson.getData(),operation);
                                }
                                else {
                                    String msg = sosListJson.getMsg();
                                    MyErrorDeal.dealError(msg,mActivity);
                                }
                            }
                            catch (Exception e)
                            {
                                e.printStackTrace();
                            }
                        }
                        else
                        {
                            MyErrorDeal.dealHttpError(response,mActivity);
                            Log.i(TAG,"onSuccess "+retCode+"return: "+s);
                        }
                    }

                    @Override
                    public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {

                        swipeLayout.setRefreshing(false);
                        swipeLayout.setLoading(false);
                        MyErrorDeal.dealHttpError(response,mActivity);

                    }
                });
    }


    public void getAllRecords(final int operation)
    {

        swipeLayout.setRefreshing(false);
        swipeLayout.setLoading(false);
		/*模拟数据START*/

        if (operation == REFRESH_LIST)
        {
            if(mSosList != null)
            {
                mSosList.clear();
            }
        }
        final String [] timeArray = new String[]{"2017-07-01 15:00","2017-07-01 18:00","2017-07-02 00:00"};



        new Thread()
        {
            public void run()
            {
                for(int i = 0; i < 3; i++) {
                    SosListItem sosListItem = new SosListItem();
                    sosListItem.setItemId(String.valueOf(i+1));
                    sosListItem.setImageUrl("");
                    sosListItem.setName("刘先生");
                    sosListItem.setAddress("西安电子科技大学");
                    sosListItem.setState(i);
                    sosListItem.setLatitude("34.231724");
                    sosListItem.setLongitude("108.91307");
                    sosListItem.setLocationTime(0);  //呼救时间
                    sosListItem.setDataTime(timeArray[i]); //模拟时间数据
                    mSosList.add(sosListItem);
                }
                mHandler.sendEmptyMessage(0);

            }

        }.start();
		/*模拟数据END*/

        return;
    }
    /**
     * 回到页面自动刷新
     */
    public void autoRefresh()
    {
        swipeLayout.post(new Runnable() {
            @Override
            public void run() {
                swipeLayout.setRefreshing(true);

            }
        });
        hasNextPage = true;
        pageIndex = 1;
        getData(REFRESH_LIST);//刷新页面


    }

    @Override
    public void onResume() {
        Log.i(TAG,"onResume");
        //gxw-getData(REFRESH_LIST);//刷新页面
        super.onResume();
    }




    @Override
    public void onDestroyView() {

        Log.i(TAG,"onDestroyView");
        if (layout != null) {
            ((ViewGroup) layout.getParent()).removeView(layout);
        }
        super.onDestroyView();

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        Log.i(TAG,"onHiddenChanged"+hidden);
        if(hidden == false)
        {
            autoRefresh();
        }
        super.onHiddenChanged(hidden);
    }

    @Override
    public void onRefresh() {
        Log.i(TAG,"onRefresh");
        hasNextPage = true;
        pageIndex = 1;
        getData(REFRESH_LIST);

    }

    @Override
    public void onLoad() {

        Log.i(TAG,"onLoad");
        if(hasNextPage)
        {
            getData(LOAD_MORE);
        }
        else {
            swipeLayout.setLoading(false);
        }

    }
}
